package cn.liuhuan1.mongoDb.fastService;

import cn.liuhuan1.mongoDb.FastUtile.FastDFSClient;
import cn.liuhuan1.mongoDb.FastUtile.FastDFSFileMeta;
import cn.liuhuan1.mongoDb.FastUtile.FastDFSFileMetaBuilder;
import cn.liuhuan1.mongoDb.fastImp.FastDfsImp;
import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Auther: liuhuan
 * @Date: 2021/4/7 - 04 - 07 - 20:39
 * @Description:
 * @version: 1.0
 */
@Service
public class FastDfsService implements FastDfsImp {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Override
    public String uploadFast(MultipartFile multipartFile) {
        try {
            FastDFSFileMeta fastDFSFileMeta = FastDFSFileMetaBuilder.build(multipartFile);
            String[] upload = fastDFSClient.upload(fastDFSFileMeta);
            return upload[0] + "/" + upload[1];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String upload(byte[] bytes,String fileName) {
            String[] upload = fastDFSClient.upload(bytes,fileName);
            if(upload == null && upload.length < 1){
                return null;
            }
            return upload[0] + "/" + upload[1];
    }

    @Override
    public String uploadFile(File file) {
        try {
            FastDFSFileMeta fastDFSFileMeta = FastDFSFileMetaBuilder.build(file);
            String[] upload = fastDFSClient.upload(fastDFSFileMeta);
            return upload[0] + "/" + upload[1];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer delFileUrl(String group, String url) {
        try {
            return fastDFSClient.delete(group,url);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
